package com.javen.springbootsecurityjwt.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @ClassName: TokenManager
 * @Description: Token工具类
 * @Author tujw
 * @Date 2021/1/18 10:58
 * @Version 1.0
 */
public class JwtTokenUtil {
    private static long tokenExpiration = 24 * 60 * 60 * 1000;
    private static String tokenSignKey = "javen";
    private static String userRoleKey = "userRole";

    public String createToken(String userName) {
        String token = Jwts.builder().setSubject(userName)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    public static String createToken(String userName, String role) {
        String token = Jwts.builder().setSubject(userName)
                .claim(userRoleKey, role)
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    public static String getUserNameFromToken(String token) {
        String userName = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        return userName;
    }

    public static String getUserRoleFromToken(String token) {
        Claims claims = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody();
        return claims.get(userRoleKey).toString();
    }

    public static void main(String[] args) {
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String userName = "you";
        String token = createToken(userName, "ROLE_ADMIN");
//        String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOlsicmVzb3VyY2VJZCJdLCJzY29wZSI6WyJhbGwiXSwib3JnUm9sZXMiOlt7ImlkIjo4NTQwNjA3NzA5NjE3MDI5MTIsIm1vZGlmeVRpbWUiOm51bGwsIm1vZGlmeVVzZXJJZCI6bnVsbCwiY3JlYXRlVGltZSI6bnVsbCwiY3JlYXRlVXNlcklkIjpudWxsLCJkZWxldGVUYWciOm51bGw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JjcmVhdGVUaW1lIjpudWxsLCJjcmVhdGVVc2VySWQiOm51bGwsImRlbGV0ZVRhZyI6bnVsbCwidXNlcklkIjpudWxsLCJhY2NvdW50SWQiOm51bGwsInVzZXJBY2NvdW50IjoidHVqdyIsInVzZXJQd2QiOm51bGwsImFjY2Vzc1Rva2VuIjoiIiwicmVmcmVzaFRva2VuIjoiIiwic291cmNlIjoxfSwidXNlck5hbWUiOiJ0dWp35raC5a625pe6IiwiZXhwIjoxNzA2NzM2OTE0LCJhdXRob3JpdGllcyI6WyIxMiIsIjEwIl0sImp0aSI6ImxPZFNlbDlNQlNrUmloQktMXzJLd0lFVG5XMCIsImNsaWVudF9pZCI6ImNsaWVudElkIn0.MGbcoT2A55oSXVpGvpdJih6-zrJPU9qz9dqVWadoyDk";
        System.out.println("生成的Token：" + token);
//        System.out.println("解析的Token：" + getUserNameFromToken(token));
    }

}
